package com.audi.adapter;

import java.util.ArrayList;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.BaseActivity;
import com.audi.R;
import com.audi.activity.DeviceDetailActivity;
import com.audi.activity.HomeControlActivity;
import com.audi.activity.SigninActivity;
import com.audi.box.objects.LocalData;
import com.audi.box.service.ConnectService;
import com.audi.dto.DeviceItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.utils.DeviceHelper;
import com.audi.view.Customdialog;
import com.audi.view.DeviceUpdatePhoto;

@SuppressWarnings("deprecation")
public class ListDeviceCardAdapterTop extends BaseAdapter {
	public static Activity mActivity;
	private DeviceUpdatePhoto mDeviceUpdatePhoto;
	private ArrayList<DeviceItem> mdeviceCardList;
	ImageView menudevicecard;
	private PopupMenu mPopMenu;
	SQLiteAsusNewHelper mSQLite;
	public static SendMessage sendMessage = new SendMessage();

	public ListDeviceCardAdapterTop(Activity activity,
			ArrayList<DeviceItem> devicecradList,
			DeviceUpdatePhoto mDeviceUpdatePhoto) {
		mActivity = activity;
		mdeviceCardList = devicecradList;
		this.mDeviceUpdatePhoto = mDeviceUpdatePhoto;
		mSQLite = new SQLiteAsusNewHelper(mActivity);
	}

	@Override
	public int getCount() {
		if (mdeviceCardList.size() > 3)
			return 4;
		else {
			return mdeviceCardList.size();
		}
	}

	@Override
	public DeviceItem getItem(int position) {
		return mdeviceCardList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	@SuppressLint("InflateParams")
	@Override
	public View getView(int position, View convertView, ViewGroup view) {
		DeviceItem item = mdeviceCardList.get(position);
		ViewHolderTop viewholder = null;
		// if (position==4) { return convertView;}
		/*
		 * if (position == 4) return convertView;
		 */
		// khoi tao cho viewholder
		if (convertView == null) {
			viewholder = new ViewHolderTop();
			convertView = LayoutInflater.from(mActivity).inflate(
					R.layout.row_device_card_top, null);

			// detail
			viewholder.imageMenu = (ImageView) convertView
					.findViewById(R.id.imv_device_tab_menu_top);
			viewholder.placeName = (TextView) convertView
					.findViewById(R.id.placeNameDeviceTop);
			viewholder.nameDevice = (TextView) convertView
					.findViewById(R.id.typeOfDeviceTop);
			viewholder.frameOnOff = (FrameLayout) convertView
					.findViewById(R.id.frame_onoff);
			// switch
			viewholder.switchDrawer = (Switch) convertView
					.findViewById(R.id.mySwitchTop);
			viewholder.img1 = (ImageView) convertView
					.findViewById(R.id.imageViewTop1);
			viewholder.img2 = (ImageView) convertView
					.findViewById(R.id.imageViewTop2);
			// temp
			viewholder.imgTemp = (ImageView) convertView
					.findViewById(R.id.img_temp);
			viewholder.layoutTemp = (FrameLayout) convertView
					.findViewById(R.id.layout_temp);
			viewholder.txtTemp = (TextView) convertView
					.findViewById(R.id.txt_temp);
			// warning
			viewholder.imageWarning = (ImageView) convertView
					.findViewById(R.id.img_warning);

			viewholder.layoutTemp.setVisibility(View.GONE);
			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.imageWarning.setVisibility(View.GONE);

			convertView.setTag(viewholder);
		} else {
			viewholder = (ViewHolderTop) convertView.getTag();
		}
		// set data for listView

		int deviceType = DeviceHelper.getGroupType(item.getDeviceType());
		if (deviceType == 0) {

			viewholder.frameOnOff.setVisibility(View.VISIBLE);
			viewholder.imageWarning.setVisibility(View.GONE);
			viewholder.layoutTemp.setVisibility(View.GONE);
			viewholder.switchDrawer.setOnCheckedChangeListener(null);

			if (item.getDeviceStatus() == 1) {
				viewholder.switchDrawer.setChecked(false);
				viewholder.switchDrawer
						.setBackgroundResource(R.drawable.icon_decive_on_big_source_txt);
				viewholder.img1.setVisibility(View.VISIBLE);
				viewholder.img2.setVisibility(View.INVISIBLE);

			} else {

				viewholder.switchDrawer.setChecked(true);
				viewholder.switchDrawer
						.setBackgroundResource(R.drawable.icon_device_off_big_txt);
				viewholder.img1.setVisibility(View.INVISIBLE);
				viewholder.img2.setVisibility(View.VISIBLE);
			}
			;
		} else if (deviceType == 1) {

			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.imageWarning.setVisibility(View.VISIBLE);
			viewholder.layoutTemp.setVisibility(View.GONE);
			if (item.getDeviceStatus() == 1) {

				viewholder.imageWarning
						.setImageResource(R.drawable.icon_warning_sensor_green_big);
			} else {
				viewholder.imageWarning
						.setImageResource(R.drawable.icon_warning_sensor_red_big);

			}
		} else

		{
			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.imageWarning.setVisibility(View.GONE);
			viewholder.layoutTemp.setVisibility(View.VISIBLE);

			viewholder.imgTemp.setImageResource(R.drawable.temp_icon_big);
			viewholder.txtTemp.setVisibility(View.VISIBLE);
			viewholder.txtTemp.setText(item.getDeviceStatus() + "");

		}

		viewholder.nameDevice.setText(item.getDeviceName());

		viewholder.placeName.setText(item.getDevicePlace());

		onclick(viewholder, position);

		return convertView;
	}

	@SuppressWarnings("deprecation")
	public void onclick(final ViewHolderTop viewholder, final int position) {
		Log.d("Griddevice", "Click on item");
		final DeviceItem ItemCurrent = mdeviceCardList.get(position);
		viewholder.switchDrawer
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked == false) {
							Log.d("switch", "Open" + position);
							
							try {
								if (LocalData.isConnectsuccess == true)
								{
								if (ConnectService.mmTcpClient != null) {
									JSONObject jsstatus = new JSONObject();
									JSONObject jsdevicestatus = new JSONObject();
									jsdevicestatus.put(""+position, false);
									jsstatus.put(LocalData.TAG_USERGROUP, LocalData.usergroup);
									jsstatus.put(LocalData.TAG, LocalData.TAG_STATUS);
									jsstatus.put(LocalData.TAG_STRJSON, jsdevicestatus.toString());									
									ConnectService.mmTcpClient
											.sendMessage(jsstatus.toString());
									Log.d("switch", "Inside try 1" + jsstatus.toString());
								}
								else {
									Toast.makeText(mActivity, "Can not connect to Server", Toast.LENGTH_SHORT).show();
									Log.e("Griddevice", "Không connect được sao mà gửi-1");									
									}
								}
								else 									
								{
									Toast.makeText(mActivity, "Can not connect to Server", Toast.LENGTH_SHORT).show();
//									Intent intt = new Intent(mActivity, Customdialog.class);
//						            intt.putExtra("mess", LocalData.strreceiver);
//						            intt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
//						            startActivity(intt);
									Log.e("Griddevice", "Không connect được sao mà gửi-2");
									}
							} catch (Exception e) {
								Log.e("Griddevice", "" + e);
							}
							viewholder.switchDrawer
									.setBackgroundResource(R.drawable.icon_decive_on_big_source_txt);
							viewholder.img1.setVisibility(View.VISIBLE);
							viewholder.img2.setVisibility(View.INVISIBLE);
							// update device
							DeviceItem newItemOpen = new DeviceItem();
							newItemOpen.setDeviceId(ItemCurrent.getDeviceId());
							newItemOpen.setDeviceStatus(1);
							sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
									newItemOpen, handlerUpdateDevice);
						} else {
							Log.d("switch", "Close 1" + position);							
							viewholder.switchDrawer
									.setBackgroundResource(R.drawable.icon_device_off_big_txt);
							/*
							 * Send lenh bat tat
							 */
							try {
								if (LocalData.isConnectsuccess == true)
								{
								if (ConnectService.mmTcpClient != null) {
									JSONObject jsstatus = new JSONObject();
									JSONObject jsdevicestatus = new JSONObject();
									jsdevicestatus.put(""+position, true);
									jsstatus.put(LocalData.TAG_USERGROUP, LocalData.usergroup);
									jsstatus.put(LocalData.TAG, LocalData.TAG_STATUS);
									jsstatus.put(LocalData.TAG_STRJSON, jsdevicestatus.toString());
									
									ConnectService.mmTcpClient
									.sendMessage(jsstatus.toString());
//									SigninActivity.mTcpClient
//											.sendMessage(position + "0");
									Log.d("switch", "Inside try 2" + jsstatus.toString());
								}
								else 
									{
									Toast.makeText(mActivity, "Can not connect to Server", Toast.LENGTH_SHORT).show();
									Log.e("Griddevice", "Không connect được sao mà gửi-1");
									
									}
								}
								else
									{
									Toast.makeText(mActivity, "Can not connect to Server", Toast.LENGTH_SHORT).show();
									Log.e("Griddevice", "Không connect được sao mà gửi-2");
									}
									
							} catch (Exception e) {

								Log.e("Griddevice", "" + e);

							}
							
							
							viewholder.img1.setVisibility(View.INVISIBLE);
							viewholder.img2.setVisibility(View.VISIBLE);
							DeviceItem newItemOpen = new DeviceItem();
							newItemOpen.setDeviceId(ItemCurrent.getDeviceId());
							newItemOpen.setDeviceStatus(0);
							sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
									newItemOpen, handlerUpdateDevice);
						}
					}
				});

		viewholder.imageMenu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mPopMenu = new PopupMenu(mActivity, viewholder.imageMenu);
				mPopMenu.getMenuInflater().inflate(
						R.menu.menu_list_device_card, mPopMenu.getMenu());
				mPopMenu.show();
				mPopMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem index) {
						// TODO Auto-generated method stub
						if (index.getItemId() == R.id.deviceMenu_editName) {

							((HomeControlActivity) mActivity)
									.renameDeviceFuntion(ItemCurrent);

							// Toast.makeText(mActivity, "Changed!", 1).show();
						}
						if (index.getItemId() == R.id.deviceMenu_editPlace) {
							// Toast.makeText(mActivity, "Changed!", 1).show();

							((HomeControlActivity) mActivity)
									.changePlaceDeviceFuntion(ItemCurrent);

						}
						if (index.getItemId() == R.id.deviceMenu_editPhoto) {
							// Toast.makeText(mActivity, "Edited!", 1).show();

							((HomeControlActivity) mActivity)
									.changePhotoDeviceFuntion(ItemCurrent);

						}
						if (index.getItemId() == R.id.deviceMenu_delete) {

							((HomeControlActivity) mActivity)
									.deleteDeviceFuntion(ItemCurrent);

							// Toast.makeText(mActivity, "Deleted!", 1).show();
						}
						return true;
					}
				});

			}
		});

		viewholder.nameDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intentDeviceCard = new Intent(mActivity,
						DeviceDetailActivity.class);
				Bundle bundleInfoDevice = new Bundle();

				bundleInfoDevice.putSerializable("item", ItemCurrent);

				intentDeviceCard.putExtras(bundleInfoDevice);
				mActivity.startActivity(intentDeviceCard);

			}
		});
		viewholder.placeName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intentDeviceCard = new Intent(mActivity,
						DeviceDetailActivity.class);
				Bundle bundleInfoDevice = new Bundle();

				bundleInfoDevice.putSerializable("item", ItemCurrent);

				intentDeviceCard.putExtras(bundleInfoDevice);
				mActivity.startActivity(intentDeviceCard);

			}
		});

	}
	
	public static class ViewHolderTop {
		private FrameLayout frameOnOff;
		private TextView nameDevice;
		private TextView txtOn;

		private TextView txtOff;
		private TextView placeName;
		// private TextView placeNameDevice;
		private ImageView imageMenu;
		private Switch switchDrawer;
		private ImageButton handle;
		private ImageView imageWarning;
		private FrameLayout layoutTemp;
		private TextView txtTemp;
		private ImageView imgTemp, img1, img2;

	}

	public void swapItems(final ArrayList<DeviceItem> mList) {
		this.mdeviceCardList = mList;

		notifyDataSetChanged();
	}
	
	/**
	 * handlerRenamePrivacyDeletePlace
	 * 
	 * @see update UI place
	 */
	@SuppressLint("HandlerLeak")
	public static android.os.Handler handlerUpdateDevice = new android.os.Handler() {

		public void handleMessage(final Message msg) {
			mActivity.runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_DEVICE)) > 0) {
								Log.d("update device", "OK!!!!");
								((BaseActivity) mActivity).onRefreshData();
							}
						}						
					} catch (Exception e) {
						Log.d("update device", "failedd"+e);
					}
					Log.d("update device", "2");
//					((BaseActivity) mActivity).onRefreshData();
				
				}
			});
		}

	};
}
